import {
  constantRoutes
} from '@/router'
import {
  getMenuList
} from '@/api/menuAPI'
import Layout from '@/layout'
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(async (r, j) => {
      try {
        let res = await getMenuList();
        let accessedRoutes = buildRoutes(res.data);
        commit('SET_ROUTES', accessedRoutes);
        r(accessedRoutes);
      } catch (error) {
        j(error);
      }
    });
  }
}

const buildRoutes = (munus) => {
  let res = [];
  munus.forEach(menu => {
    let m = {
      path: menu.path,
      component: Layout,
      children: [],
      meta: {
        title: menu.title
      }
    }
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(cmenu => {
        m.children.push({
          path: cmenu.path,
          component: (resolve) => require([`@/views${cmenu.component}`], resolve),
          meta: {
            title: cmenu.title
          }
        })
      });
    } else {
      m.children.push({
        path: '',
        component: (resolve) => require([`@/views${menu.component}`], resolve),
        meta: {
          title: menu.title
        }
      });
    }
    res.push(m);
  })
  return res;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
